<?php

namespace app\common\model;

use think\Model;
use think\facade\Cache;
/**
 * 分类模型
 */
class Category Extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $pk = 'itemid';

    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    //获取器可以定义数据表中不存在的字段
    


    // 追加属性
    // protected $append = [
    //     'type_text',
    //     'flag_text',
    // ];
    /**
    * init必须是静态方法，并且只在第一次实例化的时候执行。
    */
    public static function init(){
        self::event('after_insert', function ($row) {
            self::where('itemid',$row['pid'])->update(['child' => ['inc', 1]]);
        });
        self::event('after_delete', function ($row) {
            self::where('itemid',$row['pid'])->update(['child' => ['dec', 1]]);
        });
        self::event('after_update', function ($row) {
            self::where('itemid',$row['beforepid'])->update(['child' => ['dec', 1]]);
            self::where('itemid',$row['pid'])->update(['child' => ['inc', 1]]);
        });
    }

    public function setFlagAttr($value, $data)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }
    //刷新类别的子类数量
    public function refreshChild($pid = 0){
        $ll = $this->where('pid',$pid);
        $i = count($ll);
        $this->where('itemid',$pid)->update(['child'=>$i]);
        return true;
    }
    //根据类别编号得到类别名称
    public function getCategoryByCache($catid = 0){
        $con = array();$name = '';
        $bool = Cache::has('category'.$catid);
        if($bool){
            //如果缓存存在
            $catinfo = Cache::get('category'.$catid);
        }else{
            //如果缓存不存在
            $catinfo = $this->get($catid);
            $arr = array();
            $arr['itemid'] = $catid;
            $arr['name'] = $catinfo?$catinfo['name']:'';
            $arr['diyname'] = $catinfo?$catinfo['diyname']:'';
            Cache::set('category'.$catid,$arr);
            $catinfo = Cache::get('category'.$catid);
        }
        return $catinfo;
    }
    /**
     * 读取分类类型
     * @return array
     */
    public static function getTypeList()
    {
        $typeList = config('site.categorytype');
        foreach ($typeList as $k => &$v)
        {
            $v = __($v);
        }
        return $typeList;
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getFlagList()
    {
        return ['hot' => __('Hot'), 'index' => __('Index'), 'recommend' => __('Recommend')];
    }

    public function getFlagTextAttr($value, $data)
    {
        $value = $value ? $value : $data['flag'];
        $valueArr = explode(',', $value);
        $list = $this->getFlagList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }

    /**
     * 读取分类列表
     * @param string $type      指定类型
     * @param string $status    指定状态
     * @return array
     */
    public static function getCategoryArray($type = NULL, $status = NULL)
    {
        $list = collection(self::where(function($query) use($type, $status) {
                    if (!is_null($type))
                    {
                        $query->where('type', '=', $type);
                    }
                    if (!is_null($status))
                    {
                        $query->where('status', '=', $status);
                    }
                })->order('weigh', 'desc')->select())->toArray();
        return $list;
    }

}
